package com.e3.basdoc.tax.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.e3.basdoc.tax.dao.TaxDAO;
import com.e3.basdoc.tax.entity.TaxEntity;
import com.e3.basdoc.tax.model.TaxModel;
import com.e3.basdoc.tax.model.TaxQC;
import com.e3.basdoc.tax.service.TaxCacheManager;
import com.e3.basdoc.tax.service.TaxQueryService;
import com.e3.core.base.DAOHelper;
import com.e3.core.base.ServiceException;
import com.e3.core.base.SuperQueryService;

public class TaxQueryServiceImpl extends SuperQueryService implements TaxQueryService{
	
	private TaxDAO taxDAO;
	
	private TaxDAO getTaxDAO(){
		if(taxDAO == null){
			taxDAO = DAOHelper.createDAOInstance(TaxDAO.class);
		}
		return taxDAO;
	}

	public List<TaxModel> getTaxByCondition(TaxQC qc) throws ServiceException {
		
		List<Long> ids = getTaxDAO().getTaxIdsByCondition(qc);
		if(ids == null||ids.isEmpty()){
			return null;
		}
		
		List<TaxModel> models = new ArrayList<TaxModel>(ids.size());
		for (Long id : ids) {
			TaxModel model = getTaxById(id);
			models.add(model);
		}
		return models;
	}
	/**
	 * the method is used to load data into cache.
	 */
	public List<TaxModel> getAllTaxs() throws ServiceException {
		List<TaxEntity> entities = getTaxDAO().getAllTaxs();
		if(entities==null||entities.isEmpty()){
			return null;
		}
		List<TaxModel> models = new ArrayList<TaxModel>(entities.size());
		for (TaxEntity taxEntity : entities) {
			models.add(taxEntityToModel(taxEntity));
		}
		return models;
	}

	public TaxModel getTaxById(long id) throws ServiceException {
		TaxModel model = TaxCacheManager.INSTANCE.get(id);
		if(model==null){
			TaxEntity entity = getTaxDAO().getById(TaxEntity.class, id);
			model = taxEntityToModel(entity);
			if(model != null){
				TaxCacheManager.INSTANCE.put(model);
			}
		}
		
		return model;
	}

	public List<TaxModel> getTaxByIds(List<Long> ids)	throws ServiceException {
		if(ids == null||ids.isEmpty()){
			return null;
		}
		
		List<TaxModel> models = new ArrayList<TaxModel>(ids.size());
		for (Long id : ids) {
			TaxModel model = getTaxById(id);
			models.add(model);
		}
		
		return models;
	}

	private TaxModel taxEntityToModel(TaxEntity entity){
		
		if(entity == null){
			return null;
		}
		
		TaxModel model = new TaxModel();
		model = entityToModel(model, entity);
		
		model.setCode(entity.getCode());
		model.setName(entity.getName());
		model.setRate(entity.getRate());
		
		return model;
	}
}
